// pages/water/water.ts - 饮水记录页面

// 导入全局认证管理器
import { authManager } from '../../api/auth-manager';
const i18n = require('../../i18n/index');

// 防抖函数
function debounce(fn: (...args: any[]) => void, delay = 300) {
  let timer: number | null = null;
  return function(this: any, ...args: any[]) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

// 饮水类型图标
const TYPE_ICONS = {
  water: '💧',
  tea: '🍵',
  coffee: '☕',
  juice: '🧃',
  milk: '🥛',
  sports: '🏋️',
  other: '🥤'
};

// 饮水类型名称（默认中文，进入页面会根据当前语言替换）
const TYPE_NAMES = {
  water: '白水',
  tea: '茶水',
  coffee: '咖啡',
  juice: '果汁',
  milk: '牛奶',
  sports: '运动饮料',
  other: '其他'
};

// 星期几
const WEEKDAY = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

// 快速选择饮水量
const QUICK_AMOUNTS = [150, 200, 250, 300, 500];

// 饮水类型选项（名称会在 onLoad 中按语言替换）
const DRINK_TYPES = [
  { icon: '💧', name: '白水', value: 'water' },
  { icon: '🍵', name: '茶水', value: 'tea' },
  { icon: '☕', name: '咖啡', value: 'coffee' },
  { icon: '🧃', name: '果汁', value: 'juice' },
  { icon: '🥛', name: '牛奶', value: 'milk' },
  { icon: '🏋️', name: '运动饮料', value: 'sports' },
  { icon: '🥤', name: '其他', value: 'other' }
];

Page({
  data: {
    // 多语言
    l10n: {
      headerTitle: '',
      headerTip: '',
      loginMessage: '',
      loginDesc: '',
      loginBtn: '',
      quickAddTitle: '',
      customize: '',
      inputPlaceholder: '',
      addRecord: '',
      adding: '',
      historyTitle: '',
      allHistory: '',
      viewEarlier: '',
      loading: '',
      loadMore: '',
      noMore: '',
      expandBefore: '',
      expandAfter: '',
      collapse: '',
      customTitle: '',
      customPlaceholder: ''
    },
    l10nCancel: '',
    l10nConfirm: '',

    // 用户信息
    isLoggedIn: false,
    userName: '',

    // 快速添加相关
    quickAmounts: QUICK_AMOUNTS,
    drinkTypes: DRINK_TYPES,
    selectedAmount: 0,
    selectedType: 'water',
    isCustomAmount: false,
    customAmount: '',
    canAddRecord: false,
    isSubmitting: false,

    // 今日统计
    todayTotal: 0,
    targetAmount: 2000,
    progressPercent: 0,

    // 历史记录 - 使用与主页相同的数据结构
    historyRecords: [] as any[],
    allWaterLog: [] as any[],
    currentPage: 1,
    hasMore: true,
    isLoading: false,
    isLoadingMore: false,

    // UI状态
    showCustomModal: false,
    typeIcons: TYPE_ICONS,
    typeNames: TYPE_NAMES,
    weekday: WEEKDAY
  },

  // 语言监听器移除函数
  langUnsub: null as (() => void) | null,

  onLoad() {
    console.log('water页面加载');
    this.updateTexts();
    // 监听语言切换
    this.langUnsub = i18n.onLangChange(() => this.updateTexts());

    this.restoreFromStorage();
    this.updateProgress();
    this.loadHistoryRecords();
  },

  onShow() {
    console.log('water页面显示');
    this.updateTexts();
    this.restoreFromStorage();
    this.updateProgress();
    this.loadHistoryRecords();
  },

  onUnload() {
    if (this.langUnsub) {
      try { this.langUnsub(); } catch (_) {}
      this.langUnsub = null;
    }
  },

  updateTexts() {
    const t = (k: string) => i18n.t(`water.${k}`);
    const l10n = {
      headerTitle: t('headerTitle'),
      headerTip: t('headerTip'),
      loginMessage: t('loginMessage'),
      loginDesc: t('loginDesc'),
      loginBtn: t('loginBtn'),
      quickAddTitle: t('quickAddTitle'),
      customize: t('customize'),
      inputPlaceholder: t('inputPlaceholder'),
      addRecord: t('addRecord'),
      adding: t('adding'),
      historyTitle: t('historyTitle'),
      allHistory: t('allHistory'),
      viewEarlier: t('viewEarlier'),
      loading: t('loading'),
      loadMore: t('loadMore'),
      noMore: t('noMore'),
      expandBefore: t('expandBefore'),
      expandAfter: t('expandAfter'),
      collapse: t('collapse'),
      customTitle: t('customTitle'),
      customPlaceholder: t('customPlaceholder')
    };
    const l10nCancel = i18n.t('common.cancel');
    const l10nConfirm = i18n.t('common.ok');

    // 替换饮水类型名称
    const typeNames = {
      water: t('typeWater'),
      tea: t('typeTea'),
      coffee: t('typeCoffee'),
      juice: t('typeJuice'),
      milk: t('typeMilk'),
      sports: t('typeSports'),
      other: t('typeOther')
    } as any;

    const drinkTypes = [
      { icon: '💧', name: typeNames.water, value: 'water' },
      { icon: '🍵', name: typeNames.tea, value: 'tea' },
      { icon: '☕', name: typeNames.coffee, value: 'coffee' },
      { icon: '🧃', name: typeNames.juice, value: 'juice' },
      { icon: '🥛', name: typeNames.milk, value: 'milk' },
      { icon: '🏋️', name: typeNames.sports, value: 'sports' },
      { icon: '🥤', name: typeNames.other, value: 'other' }
    ];

    this.setData({ l10n, l10nCancel, l10nConfirm, typeNames, drinkTypes });
    try { wx.setNavigationBarTitle({ title: t('title') }); } catch (e) {}
  },

  onPullDownRefresh() {
    this.setData({ isLoading: true });
    this.restoreFromStorage();
    this.updateProgress();
    this.loadHistoryRecords();
    
    setTimeout(() => {
      this.setData({ isLoading: false });
      wx.stopPullDownRefresh();
    }, 1000);
  },

  onScrollView() {
    // 滚动事件处理
  },

  loadMoreRecords() {
    if (!this.data.hasMore || this.data.isLoadingMore) return;
    
    this.setData({ isLoadingMore: true });
    
    // 模拟加载更多数据
    setTimeout(() => {
      const moreRecords = this.generateMoreHistoryRecords();
      const updatedRecords = [...this.data.historyRecords, ...moreRecords];
      
      this.setData({
        historyRecords: updatedRecords,
        isLoadingMore: false,
        hasMore: Math.random() > 0.7
      });
    }, 1000);
  },

  // 从存储恢复数据 - 与主页保持一致
  restoreFromStorage() {
    try {
      // 使用全局认证管理器
      const isLoggedIn = authManager.isAuthenticated();
      const currentUser = authManager.getCurrentUser();
      const logs = wx.getStorageSync('waterLogs') || [];
      const userName = currentUser?.nickname || currentUser?.username || '';
      
      this.setData({ 
        isLoggedIn, 
        allWaterLog: logs, 
        userName 
      });
    } catch (e) {
      console.error('读取存储数据失败:', e);
    }
  },

  // 更新进度 - 与主页保持一致
  updateProgress() {
    const today = this.getTodayLogs();
    const total = today.reduce((s: number, it: any) => s + (it.amount || 0), 0);
    const progress = Math.min(100, Math.round((total / this.data.targetAmount) * 100));
    
    this.setData({ 
      todayTotal: total, 
      progressPercent: progress 
    });
  },

  // 获取今日日期key - 与主页保持一致
  getTodayKey(): string {
    const now = new Date();
    const y = now.getFullYear();
    const m = `${now.getMonth() + 1}`.padStart(2, '0');
    const d = `${now.getDate()}`.padStart(2, '0');
    return `${y}-${m}-${d}`;
  },

  // 获取今日记录 - 与主页保持一致
  getTodayLogs(): any[] {
    const key = this.getTodayKey();
    return (this.data.allWaterLog || []).filter((it: any) => it.date === key);
  },

  // 格式化时间 - 与主页保持一致
  formatTime(date: Date): string {
    const h = `${date.getHours()}`.padStart(2, '0');
    const m = `${date.getMinutes()}`.padStart(2, '0');
    return `${h}:${m}`;
  },

  // 加载历史记录 - 基于真实数据
  loadHistoryRecords() {
    if (this.data.isLoading) return;

    this.setData({ isLoading: true });

    // 使用真实数据而不是模拟数据
    const realRecords = this.data.allWaterLog || [];
    
    // 调试日志输出
    console.log('[水记录] 记录总数:', realRecords.length);
    console.log('[水记录] 记录示例:', realRecords.slice(0, 3));
    
    // 进行日期分组
    const groupedRecords = this.groupRecordsByDate(realRecords);
    
    console.log('[水记录] 分组后:', groupedRecords.length, '组');
    
    this.setData({
      historyRecords: groupedRecords,
      isLoading: false,
      hasMore: groupedRecords.length > 10 // 如果记录多于10条，则可以加载更多
    });
  },

  // 生成更多历史记录（用于加载更多功能）
  generateMoreHistoryRecords() {
    // 这里可以实现真实的分页加载逻辑
    // 当前保持原有的模拟数据逻辑
    return this.generateMockRecords();
  },

  // 生成模拟记录数据
  generateMockRecords() {
    const records = [];
    const types = Object.keys(TYPE_ICONS);
    const amounts = [150, 200, 250, 300, 350, 400, 500];

    for (let i = 0; i < 5; i++) {
      const now = new Date();
      const randomHours = Math.floor(Math.random() * 24 * (i + 1));
      const recordTime = new Date(now.getTime() - randomHours * 60 * 60 * 1000);

      records.push({
        id: Date.now() + Math.random(),
        amount: amounts[Math.floor(Math.random() * amounts.length)],
        type: types[Math.floor(Math.random() * types.length)],
        createTime: recordTime.toISOString(),
        note: Math.random() > 0.7 ? '随机备注' : ''
      });
    }

    return records;
  },

  // 按日期分组记录 - 适配水印页面WXML结构
  groupRecordsByDate(records: any[]) {
    const groups: { [key: string]: any } = {};
    
    // 首先确保记录按日期排序
    records.sort((a, b) => {
      // 按时间戳排序（如果有）或者回退到日期字符串比较
      if (a.id && b.id) {
        return Number(b.id) - Number(a.id);
      }
      return 0;
    });
    
    records.forEach(record => {
      // 确保我们有一个有效的日期
      const date = record.date || this.getTodayKey(); 
      
      // 正确解析日期，避免时区问题
      const dateObj = new Date(`${date}T00:00:00`);
      
      if (!groups[date]) {
        groups[date] = {
          date: date,
          dateStr: this.getDisplayDate(dateObj),
          weekday: WEEKDAY[dateObj.getDay()],
          records: [],
          total: 0,
          expanded: false // 用于展开/收起功能
        };
      }
      
      const recordType = record.type || 'water';
      groups[date].records.push({
        id: record.id,
        amount: record.amount,
        time: record.time,
        type: recordType,
        typeName: (this.data.typeNames as any)[recordType] || '饮水',
        icon: TYPE_ICONS[recordType as keyof typeof TYPE_ICONS] || '💧'
      });
      
      groups[date].total += record.amount || 0;
    });

    // 按日期排序，最新的在前面
    return Object.values(groups).sort((a: any, b: any) => {
      // 确保日期比较正确，添加时间部分避免时区问题
      const dateA = new Date(`${a.date}T00:00:00`);
      const dateB = new Date(`${b.date}T00:00:00`);
      return dateB.getTime() - dateA.getTime();
    });
  },

  // 选择快速添加数量
  selectAmount(e: any) {
    const amount = Number(e.currentTarget.dataset.amount);
    this.setData({
      selectedAmount: amount,
      isCustomAmount: false,
      customAmount: ''
    });
    this.updateCanAddRecord();
  },

  // 开始自定义输入
  startCustomAmount() {
    this.setData({
      selectedAmount: 0,
      isCustomAmount: true,
      customAmount: ''
    });
    this.updateCanAddRecord();
  },

  // 自定义数量输入
  onCustomAmountInput(e: any) {
    const value = e.detail.value;
    this.setData({
      customAmount: value
    });
    this.updateCanAddRecord();
  },

  // 选择饮水类型
  selectType(e: any) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      selectedType: type
    });
    this.updateCanAddRecord();
  },

  // 更新是否可以添加记录
  updateCanAddRecord() {
    const { selectedAmount, isCustomAmount, customAmount, selectedType } = this.data;
    const amount = isCustomAmount ? Number(customAmount) : selectedAmount;
    const canAdd = amount > 0 && !!selectedType && !this.data.isSubmitting;
    
    this.setData({
      canAddRecord: canAdd
    });
  },

  // 处理添加记录 - 与主页保持一致
  handleAddRecord() {
    if (!this.data.canAddRecord || !this.data.isLoggedIn) return;

    const { selectedAmount, isCustomAmount, customAmount, selectedType } = this.data;
    let amount = isCustomAmount ? Number(customAmount) : selectedAmount;
    
    if (!amount || amount <= 0) {
      wx.showToast({
        title: i18n.t('water.toastInvalid'),
        icon: 'none'
      });
      return;
    }

    if (amount > 2000) {
      wx.showToast({
        title: i18n.t('water.toastMaxExceeded'),
        icon: 'none'
      });
      return;
    }

    this.setData({ isSubmitting: true });

    // 添加记录 - 与主页逻辑一致
    const now = new Date();
    const record = {
      id: `${now.getTime()}`,
      amount,
      time: this.formatTime(now),
      type: selectedType,
      date: this.getTodayKey()
    };

    const allLogs = [record, ...this.data.allWaterLog];
    
    this.setData({
      allWaterLog: allLogs,
      selectedAmount: 0,
      isCustomAmount: false,
      customAmount: '',
      canAddRecord: false,
      isSubmitting: false
    });

    // 保存到存储
    try {
      wx.setStorageSync('waterLogs', allLogs);
      console.log('[添加记录] 成功保存到存储, 总记录数:', allLogs.length);
    } catch (e) {
      console.error('保存数据失败:', e);
    }

    // 更新UI
    this.updateProgress();
    
    // 强制重新加载历史记录
    setTimeout(() => {
      console.log('[添加记录] 延迟加载历史记录');
      this.loadHistoryRecords();
    }, 100);

    wx.showToast({
      title: i18n.t('water.toastAdded'),
      icon: 'success'
    });
  },

  // 展开某日记录
  expandDayRecords(e: any) {
    const date = e.currentTarget.dataset.date;
    const historyRecords = this.data.historyRecords.map((day: any) => {
      if (day.date === date) {
        return { ...day, expanded: true };
      }
      return day;
    });
    
    this.setData({ historyRecords });
  },

  // 收起某日记录
  collapseDayRecords(e: any) {
    const date = e.currentTarget.dataset.date;
    const historyRecords = this.data.historyRecords.map((day: any) => {
      if (day.date === date) {
        return { ...day, expanded: false };
      }
      return day;
    });
    
    this.setData({ historyRecords });
  },

  // 加载全部历史记录
  loadAllHistory() {
    // 展开所有记录
    const historyRecords = this.data.historyRecords.map((day: any) => ({
      ...day,
      expanded: true
    }));
    
    this.setData({ historyRecords });
    
    wx.showToast({
      title: i18n.t('water.allHistory'),
      icon: 'success'
    });
  },

  // 查看更早记录
  navigateToHistory() {
    wx.showToast({
      title: i18n.t('water.viewEarlier'),
      icon: 'none'
    });
    // 这里可以添加跳转到专门的历史记录页面的逻辑
  },

  // 显示自定义输入弹窗
  showCustomInput() {
    this.setData({
      showCustomModal: true,
      customAmount: ''
    });
  },

  // 隐藏自定义输入弹窗
  hideCustomInput() {
    this.setData({
      showCustomModal: false,
      customAmount: ''
    });
  },

  // 添加自定义数量
  addCustom() {
    const amount = Number(this.data.customAmount);
    
    if (!amount || amount <= 0) {
      wx.showToast({
        title: i18n.t('water.toastInvalid'),
        icon: 'none'
      });
      return;
    }

    // 执行添加逻辑
    this.setData({
      selectedAmount: 0,
      isCustomAmount: true,
      customAmount: amount.toString()
    });
    
    this.hideCustomInput();
    this.handleAddRecord();
  },

  // 格式化日期
  formatDate(date: Date): string {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 获取显示日期
  getDisplayDate(date: Date): string {
    const today = new Date();
    const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
    
    if (this.formatDate(date) === this.formatDate(today)) {
      return i18n.t('water.today');
    } else if (this.formatDate(date) === this.formatDate(yesterday)) {
      return i18n.t('water.yesterday');
    } else {
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const pattern = i18n.t('water.dateFmt');
      return pattern.replace('{month}', String(month)).replace('{day}', String(day));
    }
  },

  // 跳转到登录页面
  goToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    });
  }
});